/*
 * 节点备份文件
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "pthread.h"
#include "project.h"
#include "node_backup.h"
#include "util.h"

/*
 * 将哈希表和二叉树备份到外部文件中
 */
void *
backup_tree(void *msg)
{
    /* 每隔BACKUP_TIME时间备份缓存 */
    char *backup_file = concat_path_name(PROFILEPATH, BACKFILE);
    for (;;)
    {
        sleep(2);
        int back_fd = open(backup_file, O_RDWR);
        int i;
        for (i = 0; i < HASH_TABLE_SIZE; i++)
        {
            if (f_hash_arr[i].ha_file != NULL)
            {
                //show_innerfix(f_hash_arr[i].ha_file);
                backFFILE(f_hash_arr[i].ha_file, back_fd);
            }
        }
        close(back_fd);
    }
    
    free(backup_file);
    pthread_exit(NULL);
}

/*
 * 递归保存
 */
void
backFFILE(F_FILE T, int fd)
{
    if (!T)
        return;                     
    
    char *saveSec = createBackSection(T);
    write(fd, saveSec, strlen(saveSec));
    free(saveSec);

    backFFILE(T->left, fd);
    backFFILE(T->right, fd);
}

/*
 * 根据文件节点生成保存字段
 * [fl_name,fl_count,fl_size]
 */
char *
createBackSection(F_FILE T)
{
    if (!T)
        return NULL;

    char *sec = (char *) malloc(SECTION_LENGTH);
    sprintf(sec, "[%s,%u,%lu]", T->fl_name, T->fl_count, T->fl_size);

    return sec;
}